package com.zlsy.learning.leetcode.stack.s224;

import java.util.Stack;

/**
 * @author zhouliang
 * @date 2020/8/11 19:03
 */
public class Calculate {

  public static int calculate(String s) {
    Stack<Integer> stack = new Stack<>();
    int operate = 0;
    int result = 0;
    int sign = 1;
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      // 如果当前的字符为数字
      if (Character.isDigit(ch)) {
        operate = 10 * operate + (ch - '0');
      } else if (ch == '+') {
        result = result + operate * sign;
        operate = 0;
        sign = 1;
      } else if (ch == '-') {
        result = result + operate * sign;
        operate = 0;
        sign = -1;
      } else if (ch == '(') {
        // 入栈
        stack.push(result);
        stack.push(sign);

        operate = 0;
        sign = 1;
        //push完就是相当于把前面的结果都闭环存在栈里面了
        result = 0;
      } else if (ch == ')') {
        // 出栈，回执)之前的结果
        result = result + operate * sign;
        result = result * stack.pop();
        result = result + stack.pop();

        operate = 0;
        sign = 1;
      }
    }

    return result + (operate * sign);
  }

  public static void main(String[] args) {
    String s = "1+2+3+4-4-3-2-1";
    int calculate = calculate(s);
    System.out.println(calculate);
  }
}
